package com.fsnbigdata.web;

import com.fsnbigdata.domain.Enterprise;
import com.fsnbigdata.domain.dto.NamingPair;
import com.fsnbigdata.domain.query.EnterpriseQueryDslBinder;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.service.api.EnterpriseService;
import com.fsnbigdata.util.ReflectUtil;
import com.fsnbigdata.util.SortTools;
import com.querydsl.core.types.Predicate;
import io.springlets.data.domain.GlobalSearch;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * = EnterprisesCollectionJsonController
 *
 * TODO Auto-generated class documentation
 *
 */
@RooController(entity = Enterprise.class, pathPrefix = "/api", type = ControllerType.COLLECTION)
@RooJSON
@RestController
@RequestMapping(value = "/api/enterprises", name = "EnterprisesCollectionJsonController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "Enterprises", description = "生物企业及企业家信息数据库" )
public class EnterprisesCollectionJsonController {

    /**
     * TODO Auto-generated attribute documentation
     *
     */
    @Autowired
    private EnterpriseService enterpriseService;


    @GetMapping(name = "index", value = "index")
    public ResponseEntity<List<NamingPair>> category(
        @ApiParam @RequestParam(required = false) String initial) {
        List<NamingPair> namingPairs = enterpriseService.findAllByInitial(initial);
        return ResponseEntity.ok(namingPairs);
    }
    
    /**
     * 根据类型查询产品库数据
     */
    @GetMapping(name = "search", value = "show")
    public List<List<Enterprise>> show() {
        return enterpriseService.findAllByType();
    }

    /**
     * 自定义搜索
     * @param
     * @param
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "customSearch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public List getList(HttpServletRequest request,Pageable pageable){
        String name = request.getParameter("name");//关键字
        String content = request.getParameter("content");//desc或asc
        String value = request.getParameter("value");//字段名称
        String type = request.getParameter("type");//类型
        String legalPerson = request.getParameter("legalPerson");//法人
        String organizationCode = request.getParameter("organizationCode");//组织机构代码
        String category = request.getParameter("category");
        String enterPriseName = request.getParameter("enterPriseName");
        String productName = request.getParameter("productName");


        List enterprises=null;
        if (StringUtils.isNotEmpty(content)&&StringUtils.isNotEmpty(value)){
            Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),SortTools.basicSort(content,value));
            enterprises=enterpriseService.findByPageAndSize(type,legalPerson,organizationCode,name,category,enterPriseName,productName,pageable1);
        }else{
            enterprises=enterpriseService.findByPageAndSize(type,legalPerson,organizationCode,name,category,enterPriseName,productName,pageable);
        }
        return enterprises;
    }
    /**
     * 根据id查询详情
     * @param request
     * @return
     */
    @GetMapping(name = "find" , value="find")
    public Enterprise findById(HttpServletRequest request){
        return enterpriseService.findOne(Long.parseLong(request.getParameter("id")));
    }

    /**
     * 根据id 降序排序
     */
    @GetMapping(name = "search", value = "sortByIdAndDesc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Enterprise>> sortByIdAndDesc(
            @ApiParam @QuerydslPredicate(root = Enterprise.class, bindings = EnterpriseQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(), SortTools.basicSort("DESC","id"));
        Page<Enterprise> enterprises=enterpriseService.search(predicate, pageable1);
        return ResponseEntity.ok(enterprises);
    }
    /**
     * 根据id 升序排序
     */
    @GetMapping(name = "search", value = "sortByIdAndAsc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Enterprise>> sortByIdAndAsc(
            @ApiParam @QuerydslPredicate(root = Enterprise.class, bindings = EnterpriseQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(), SortTools.basicSort("ASC","id"));
        Page<Enterprise> enterprises=enterpriseService.search(predicate, pageable1);
        return ResponseEntity.ok(enterprises);
    }
    /**
     * @param query
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "search")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Enterprise>> search(
            @ApiParam @RequestParam(required = false) String query,
            Pageable pageable) {
        GlobalSearch globalSearch = StringUtils.isNotBlank(query) ? new GlobalSearch(query, false) : null;
        Page<Enterprise> enterprises = enterpriseService.findAll(globalSearch, pageable);
        return ResponseEntity.ok(enterprises);
    }

    /**
     *
     * @param predicate
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "advanceSearch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Enterprise>> advanceSearch(
            @ApiParam @QuerydslPredicate(root = Enterprise.class, bindings = EnterpriseQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Page<Enterprise> enterprises = enterpriseService.search(predicate, pageable);
        return ResponseEntity.ok(enterprises);
    }


    /**
     * @param authentication
     * @param query
     * @param pageable
     * @return
     */
    @GetMapping(name = "list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    @PreAuthorize("hasRole('DB_ENTERPRISE')")
    public ResponseEntity<Page<Enterprise>> list(
            Authentication authentication,
            @ApiParam @RequestParam(required = false) String query,
            Pageable pageable) {
        GlobalSearch globalSearch = StringUtils.isNotBlank(query) ? new GlobalSearch(query, false) : null;
        Page<Enterprise> enterprises = null;
        List<String> authorities = authentication.getAuthorities().stream().map(it -> it.getAuthority()).collect(Collectors.toList());
        if(!authorities.contains("ROLE_USER_ADMIN")){
            enterprises = enterpriseService.findAll(globalSearch, pageable, authentication.getName());
        }else{
            enterprises = enterpriseService.findAll(globalSearch, pageable);
        }

        return ResponseEntity.ok(enterprises);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return UriComponents
     */
    public static UriComponents listURI() {
        return MvcUriComponentsBuilder.fromMethodCall(MvcUriComponentsBuilder.on(EnterprisesCollectionJsonController.class).list( null,null, null)).build().encode();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param enterprise
     * @param result
     * @return ResponseEntity
     */
    @PostMapping(name = "create")
    @PreAuthorize("hasRole('DB_ENTERPRISE')")
    @ApiOperation(value = "",notes = "save")
    public ResponseEntity<?> create(
            @RequestBody @Valid  Enterprise enterprise,
            BindingResult result,
            Principal principal) throws Exception {

        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }

        if (enterprise.getId() != null || enterprise.getVersion() != null) {
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }

        enterprise.setCreator(principal.getName());

        Enterprise newEnterprise = enterpriseService.save(enterprise);
        UriComponents showURI = EnterprisesItemJsonController.showURI(newEnterprise);

        Class<?> clazz = EnterprisesCollectionJsonController.class;
        Method method = clazz.getMethod("create", ReflectUtil.getPeremeterClass(clazz, "create"));
        ReflectUtil.setAnnotationOn(method,"新增企业库，名称："+newEnterprise.getName());

        return ResponseEntity.ok(newEnterprise);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param enterprises
     * @param result
     * @return ResponseEntity
     */
    @PostMapping(value = "/batch", name = "createBatch")
    @ApiIgnore
    public ResponseEntity<?> createBatch(@Valid @RequestBody Collection<Enterprise> enterprises, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        }
        enterpriseService.save(enterprises);
        return ResponseEntity.created(listURI().toUri()).build();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param enterprises
     * @param result
     * @return ResponseEntity
     */
    @PutMapping(value = "/batch", name = "updateBatch")
    @ApiIgnore
    public ResponseEntity<?> updateBatch(@Valid @RequestBody Collection<Enterprise> enterprises, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        }
        enterpriseService.save(enterprises);
        return ResponseEntity.ok().build();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ids
     * @return ResponseEntity
     */
    @DeleteMapping(value = "/batch/{ids}", name = "deleteBatch")
    @ApiIgnore
    public ResponseEntity<?> deleteBatch(@PathVariable("ids") Collection<Long> ids) {
        enterpriseService.delete(ids);
        return ResponseEntity.ok().build();
    }
}
